﻿using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XH.DataUpload.Entities;
using XH.DataUpload.Service;

namespace XH.DataUpload.Client.ViewModels
{
    public class LoginViewModel : BindableBase, IDialogAware
    {
        public string Title => "用户登录";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog() => true;

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {

        }

        private string _userName;

        public string UserName
        {
            get { return _userName; }
            set { SetProperty<string>(ref _userName, value); }
        }

        private string _password;

        public string Password
        {
            get { return _password; }
            set { SetProperty<string>(ref _password, value); }
        }


        public DelegateCommand btnLogin { get; set; }
        public DelegateCommand LoginCommand { get; set; }
        public DelegateCommand ExitCommand { get; set; }

        private readonly IUserService _userService;
        public LoginViewModel(IUserService userService)
        {
            _userService = userService;

            LoginCommand = new DelegateCommand(DoLogin);
            ExitCommand = new DelegateCommand(DoExit);

                btnLogin = new DelegateCommand(new Action(() => {
                    RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
                }));

        }

        private void DoExit()
        {
            DialogResult dialog = new DialogResult(ButtonResult.Cancel);
            RequestClose?.Invoke(dialog);
        }

        private void DoLogin()
        {
            try
            {
                SysUser user = _userService.Login(UserName, Password);
                if (user == null) throw new Exception("用户名密码错误，请重试");

                DialogResult dialog = new DialogResult(ButtonResult.OK);
                RequestClose?.Invoke(dialog);
            }
            catch (Exception ex)
            {
                Logger.LogQueue.ExceptionLogQueue.Enqueue(ex.Message);
            }
        }
    }
}
